<template>
  <div class="autoGrow flex-column" style="overflow: hidden;position: relative;">

    <div ref="scrollview" class="chatBox autoGrow flex-column" @scroll="scroll">
      <div ref="scroller" class="scroller">
      <div @click="()=>$emit('openHistoryDialog')" style="line-height: 30px; padding: 0 15px; border-radius: 3px; background-color: #e2e2e2; cursor: default; font-size: 14px;width: 100px; text-align: center; margin: 0 auto;">更多聊天记录</div>
      <messageFall v-if="1" :account="account" :data="messages" :chat="chat" @deleteUser="$emit('deleteUser',$event)" @groupReply="$emit('groupReply',$event)" @atUser="$emit('atUser',$event)"></messageFall>
      <div v-else :class="['flex-row', 'chatItem', +message.chatfrom===1 && 'self']" v-for="(message) in messages" :key="message.id">
        <system-message
           v-if="message.msgtype === 8 || message.msgtype === 9 "
          :data="message.content"
          @quit="quitGroup(message)"
        />
        <template v-else>
          <el-tooltip
            placement="top-start"
            :disabled=" message.friendwxid && message.friendwxid.indexOf('@chatroom') < 0 || message.chatfrom===1"
            popper-class="message-tool-tip">
            <img class="chatAvatar" :src="getAvater(message)||defaultAvatar" alt="">
            <div slot="content">
                <el-button-group>
                  <el-button @click="click('groupReply', message)" class="message-tool-button" type="info" size="mini">群回复</el-button>
                  <el-button @click="click('atUser', message)" class="message-tool-button" type="info" size="mini">@他</el-button>
                  <el-button v-if="isOwner" @click="click('deleteUser', message)" class="message-tool-button" type="info" size="mini">踢出群群</el-button>
                  <el-button @click="click('addFriend', message)" class="message-tool-button" type="info" size="mini">加好友</el-button>
                </el-button-group>
              </div>
          </el-tooltip>
          <div class="messageWrap">
            <div style="color:#b4b1b1;font-size:12px;margin-bottom:5px;" v-if="isGroup && message.realFromNick">{{message.realFromNick}}</div>
            <div class="status-wrap" :style="{ 'flex-direction': message.chatfrom===1?'row':'row-reverse' }">
              <i v-if="message.msgtype===14 && message.sendstatus===0 && typeof message.cmdid==='number' " class="el-icon-success message-join"></i>
              <i v-else-if="message.msgtype===14 && message.sendstatus===20005 && typeof message.cmdid==='number' " class="el-icon-success message-join"></i>
              <i v-else-if="message.sendstatus==-100" class="el-icon-loading message-loading"></i>
              <el-popover
                v-else-if="message.sendstatus!=0 && message.sendstatus!=-100 "
                placement="top"
                title=""
                width="50"
                v-model="message.popover"
                trigger="click">
                <p v-if="message.msgtype===14 && message.chatfrom===2">失败原因：<br />{{message.sendstatus+':'+wechatCode[message.sendstatus]}}</p>
                <div v-else>
                  <p>失败原因：<br />{{message.sendstatus+':'+wechatCode[message.sendstatus]}}，是否重新发送？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="message.popover = false">取消</el-button>
                    <el-button type="primary" size="mini" @click="click('repeat',message),message.popover = false;">确定</el-button>
                  </div>
                </div>

                <i slot="reference" class="el-icon-warning message-error"></i>
              </el-popover>


              <el-tooltip placement="top" popper-class="message-tool-tip" :disabled="![1,2,4,6].includes(message.content.msgtype)">
                <message-item @click="messageClick(message)" :reply="message" :deletable="false"></message-item>
                <div slot="content">
                  <el-button-group>
                    <el-button @click="handleClipboard(message,$event)" v-if="message.content.msgtype===1" class="message-tool-button" type="info" size="mini">复制</el-button>
                    <!-- <el-button @click="revokeMsg(message)" v-if="message.chatfrom===1" class="message-tool-button" type="info" size="mini">撤回</el-button> -->
                    <el-button @click="scanImage(message)" v-if="message.content.msgtype===2&&message.chatfrom===2" class="message-tool-button" type="info" size="mini">识别二维码</el-button>
                    <el-button @click="downloadFromBrowser(message)" v-if="[2,4,6].includes(message.content.msgtype)" class="message-tool-button" type="info" size="mini">下载</el-button>
                  </el-button-group>
                </div>

              </el-tooltip>
            </div>

          </div>
          <div v-if="message.createtime" class="fontGrey sendTime">{{ formatTime(message.createtime)  }}</div>
        </template>

      </div>
      </div>
    </div>

    <div @click="tipClick" v-if="manual&&tip" class="layui-anim layui-anim-up flex-column" style="position: absolute; bottom: 10px;width:100%;align-items: center;">
      <div style="background-color: rgba(95, 184, 120, 0.5);border-radius: 15px;height: 30px;width: 100px;text-align: center;line-height: 30px;color: #fff;font-size: 14px;">有新消息</div>
    </div>
  </div>

</template>
<script>
import MessageItem from '@/components/messageItem'
import SystemMessage from '@/components/systemMessage'
import messageFall from '@/views/service/message-fall';

import { throttle,downloadFromBrowser } from '@/lib/utils'
import wechatCode from '@/lib/wechat-code'
import { mapState, mapActions, mapMutations } from 'vuex';
import Clipboard from 'clipboard'
import {pathOr} from 'ramda'


export default {
  name: "chatBox",
  data(){
    return {
      manual:false,
      lastmsgid:0,
      tip:false,
      wechatCode
    }
  },
  props: {
    list: {
      type: Array,
      default() {
        return []
      }
    },
    chatType: {
      type: String,
      default: 'user' // group
    },
    isOwner:{
      type:Boolean,
      default:false
    }
  },
  components: {
    MessageItem,
    SystemMessage,messageFall
  },
  computed:{
    ...mapState(['currentUser','currentService','messageMap','uistate','chatMap','accountMap','messageListMap','groupMemberMap']),
    chat(){
      return this.chatMap[this.uistate.chatid]
    },
    chatid(){
      return this.uistate.chatid
    },
    chat(){
      const chatid = this.uistate.chatid
      return this.chatMap[chatid]
    },
    isGroup(){
      return this.chat.friendwxid.endsWith('@chatroom')
    },
    account(){
      return this.accountMap[this.uistate.accountid]
    },
    members(){
      const key = this.prefix
      const members = this.groupMemberMap[key]
      return members
    },
    prefix(){
      const chat = this.chat ||{}
      const { csid,wxaccount,friendwxid } = chat
      const key = csid+'_'+wxaccount+'_'+friendwxid+'_'
      return key
    },
    messages(){
      return this.list.map(id=>this.getMessageById(id))
    }
  },
  watch:{
    'uistate.chatid':function(val,oldval){
      this.manual = false
    },
    list(newMap,oldMap){
      if(typeof oldMap[0] === 'undefined')this.manual = false
      if( newMap[newMap.length-1]!==oldMap[oldMap.length-1] ){
        const _msg = this.messageMap[newMap[newMap.length-1]]||{}
        if(_msg.chatfrom!==1){
          this.tip = true
        }else{
          this.manual = false
          this.tip = false
        }
      }
      this.scrollToEnd()
    },
    chats(chats=[]){
      if(chats[chats.length-1] && +chats[chats.length-1].chatfrom===1){
        this.manual = false
      }
      // todo 加载衔接
      if(this.lastmsgid != _lastmsgid){
        this.scrollToEnd()
      }
      const _lastmsgid = chats[chats.length-1]?chats[chats.length-1].msgid:0
      if(this.lastmsgid!==0 && this.lastmsgid!=_lastmsgid){
        this.tip = true
        console.log('显示')
      }

      this.lastmsgid = _lastmsgid
    }
  },
  methods: {
    ...mapMutations(['updateMessageMap']),
    getAvater(message){
      const account = this.account;
      const chat = this.chat
      const prefix = this.prefix
      let src = ''

      if(+message.chatfrom===1){
        src = account.avatar
      }else if(+message.chatfrom===2){

        if( message.realFromWxId ){
          const groupMember = this.groupMemberMap[prefix+message.realFromWxId]||{}
          src = groupMember.avatar
        }else{
          src = chat.avatar
        }
      }

      return src
    },
    getMessageById(messageid){
      let message = this.messageMap[messageid];

      let content;
      if(typeof message === 'undefined'){
        return {}
      }
      if(typeof message.content!=='object'){
        try {
          content = JSON.parse(message.content) // reply.content 返回null 结果null
        } catch (error) {
          content = { msgtype:message.msgtype,content:message.content }
        }
      }else{
        content = message.content
      }
      message.content = content;

      return message
    },
    click(type, chat) {
      this.$emit(type, chat)
    },
    messageClick(message){
      if(message.msgtype === 14){
        const { wxaccount, msgid, friendwxid,id } = message
        if( !wxaccount && !msgid && !friendwxid )return;
        this.$confirm('是否加入群聊?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.chat.joinGroup({ wxAccount:wxaccount,msgId:msgid,friendWxId:friendwxid,chatId:id })
            .then(e=>{
              this.$message({
                type: 'success',
                message: '任务提交成功!'
              });
              this.updateMessageMap({id,sendstatus:-100})
            })
        }).catch(() => {

        });
        // this.$api.chat.joinGroup()
      }
      console.log(message)
    },
    tipClick(){
      this.manual = false
      this.tip = false
      this.scrollToEnd()
    },
    scrollToEnd(){
      const scrollview = this.$refs['scrollview']
      const scroller = this.$refs['scroller']
      if(scrollview&&!this.manual)this.$nextTick(()=>scrollview.scrollTo(0,scroller.offsetHeight))
    },
    scroll:throttle(function(e){
      const scrollview = this.$refs['scrollview']
      const scroller = this.$refs['scroller']
      const { paddingTop,paddingBottom } = getComputedStyle(scrollview)
      const padding = parseInt(paddingTop)+ parseInt(paddingBottom)

      if(this.list.length > 0)
        this.manual = true  // 滚动停止
      if( scroller.offsetHeight <= padding - 24 + scrollview.offsetHeight +scrollview.scrollTop ){
        this.manual = false  // 底部
        this.tip = false
      }

    },200,{ leading:true }),

    scanImage( item ){
      const { csid,msgid,id } = item;

      this.$prompt('你需要发送验证申请，等对方通过', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue:'你好'
        }).then(({ value }) => {
          this.$api.chat.scanImage({chatId:id,message:value, csId:csid})
          .then(e=>{
            this.$message({
              type: 'success',
              message: '发送成功'
            });
          }).catch(()=>{
            this.$message({
              type: 'error',
              message: '发送失败'
            });
          })

        }).catch(() => {

        });



    },
    handleClipboard(item, event) {
      if(item && item.content){
        try {
          const message = item
          if(message.content){
            this.copy(message.content.content,event)
          }else{
            this.$message({
              showClose: true,
              message: '复制失败',
              type: 'error'
            });
          }
        } catch (error) {
          this.$message({
            showClose: true,
            message: '复制失败',
            type: 'error'
          });
        }
      }


    },
    copy(text, event){
      const clipboard = new Clipboard(event.target, {
        text: () => text
      })
      clipboard.on('success', () => {
        this.$message({
          showClose: true,
          message: '复制成功',
          type: 'success'
        });
        clipboard.destroy()
      })
      clipboard.on('error', () => {
        this.$message({
          showClose: true,
          message: '复制失败',
          type: 'error'
        });
        clipboard.destroy()
      })
      clipboard.onClick(event)
    },
    downloadFromBrowser(message){
      const src = pathOr('',[ 'content','src' ],message)
      const data = pathOr('',[ 'content','data' ],message)
      if(src||data){
        const loadurl = src?(this.config.apiUrl+src):('data:image/png;base64,'+data)
        downloadFromBrowser( loadurl )
      }
    },
    revokeMsg(message){

    },
    quitGroup(message){
      const { csid:csId,wxaccount:wxAccount,friendwxid:groupNo } = message
      const params = {
        csId,
        wxAccount,
        groupNo
      }
      this.$api.group.quitGroup(params)
        .then(rs=>{
          this.$message({
            type:'success',
            message:'任务创建成功'
          })
        })
        .catch(e=>{
          this.$message({
            type:'error',
            message:e
          })
        })
    }


  }
}

</script>
<style scoped>
.chatBox .chatItem img{
  border-radius: 3px
}
.chatBox .chatItem:hover .messageWrap .qucikOperate{
  display: flex
}
.chatBox .chatItem .messageWrap{
  z-index: 1;
}
.message-tool-button{
  background: #303133;
  border-color: #303133;
}
.status-wrap{
  display: flex;
  flex-direction: row;
}
.status-wrap .message-error{
  color: #F56C6C;
  font-size: 20px;
  margin: 10px;
}
.status-wrap .message-loading{
  margin: 10px;
  font-size: 20px;
  width: 20px;
  height: 20px;
  color: #666;
}
.status-wrap .message-join{
  margin: 10px;
  font-size: 20px;
  width: 20px;
  height: 20px;
  color: #67C23A;
}
</style>
<style>
.el-tooltip__popper.message-tool-tip{
  padding: 0
}
</style>
